package main

import (
	"crypto/tls"
	"errors"
	"fmt"
	"net/http"
	"net/http/httputil"
	"os"
)

// 实现自动探测远端是HTTP还是HTTPS的反向代理。

func main() {
	hostPort := os.Args[1]

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		url := *r.URL
		url.Host = hostPort
		url.Scheme = "https"
		proxy := httputil.NewSingleHostReverseProxy(&url)
		proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
			var headerErr tls.RecordHeaderError
			if errors.As(err, &headerErr) {
				u := url
				u.Scheme = "http"
				p := httputil.NewSingleHostReverseProxy(&u)
				p.ServeHTTP(w, r)
			} else {
				w.WriteHeader(500)
				w.Write([]byte(err.Error()))
			}

		}
		proxy.ServeHTTP(w, r)
	})

	fmt.Println("running")
	http.ListenAndServe(":1080", nil)
}
